package com.quzi.kettle.push;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.utils.MSharePerference;

public class MQTTService extends Service {

    private MqttClient mqttClient;

    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
    	
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
		            mqttClient = new MqttClient(GlobalConfig.BROKER_URL, GlobalConfig.clientId, new MemoryPersistence());
		            mqttClient.setCallback(new PushCallback(MQTTService.this));
		            MqttConnectOptions options = new MqttConnectOptions();
		            options.setCleanSession(true);
		            options.setConnectionTimeout(5000);
		            options.setUserName(GlobalConfig.userName);
		            options.getKeepAliveInterval();
		            options.setPassword(GlobalConfig.passWord.toCharArray());
		            mqttClient.connect(options);
		            String topic = MSharePerference.getInstance(getApplicationContext()).get(GlobalConfig.MAC);
		            if(topic.isEmpty()){
		            	
		            }else{
		            		mqttClient.subscribe(GlobalConfig.Filter_Send+topic);
		            		mqttClient.subscribe(GlobalConfig.Filter_Receive+topic);
		            		Log.d("mmqtt","订阅 "+GlobalConfig.Filter_Send+topic+"    "+GlobalConfig.Filter_Receive+topic);
		            }
		        } catch (MqttException e) {
		        	
		        	Log.d("mmqtt","Something went wrong!!!");
		            e.printStackTrace();
		        }

			}
		}).start();
        
        super.onStart(intent, startId);
    }

    
    
    @Override
    public void onDestroy() {
        try {
            mqttClient.disconnect(0);
        } catch (MqttException e) {
            Toast.makeText(getApplicationContext(), "Something went wrong!" + e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}
